package com.luoshizhen.lease.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luoshizhen.lease.model.entity.BrowsingHistory;
import com.luoshizhen.lease.web.app.mapper.BrowsingHistoryMapper;
import com.luoshizhen.lease.web.app.service.BrowsingHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoshizhen.lease.web.app.vo.history.HistoryItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;

    /**
     * 根据用户ID分页查询历史记录项
     *
     * @param page 分页对象，包含分页查询所需的信息，如当前页数、页面大小等
     * @param userId 用户ID，用于查询该用户的历史记录
     * @return 返回一个分页的历史记录项对象，包含查询到的历史记录数据
     */
    @Override
    public IPage<HistoryItemVo> pageHistoryItemByUserId(Page<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.pageHistoryItemByUserId(page, userId);
    }

    @Override
    @Async
    /**
     * 异步保存用户浏览历史记录
     * 如果用户已经浏览过该房间，则更新浏览时间；
     * 否则，创建新的浏览历史记录
     *
     * @param userId 用户ID
     * @param roomId 房间ID
     */
    public void saveHistory(Long userId, Long roomId) {
        // 输出保存浏览历史的线程信息
        System.out.println("保存浏览历史-"+Thread.currentThread().getName());

        // 创建查询条件，查找用户是否已经浏览过该房间
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId, userId);
        queryWrapper.eq(BrowsingHistory::getRoomId, roomId);

        // 执行查询，获取浏览历史记录
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);

        // 如果查询到浏览历史记录，则更新浏览时间
        if (browsingHistory != null) {
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);
        } else {
            // 如果没有查询到浏览历史记录，则创建新的浏览历史记录并插入数据库
            BrowsingHistory newBrowsingHistory = new BrowsingHistory();
            newBrowsingHistory.setUserId(userId);
            newBrowsingHistory.setRoomId(roomId);
            newBrowsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.insert(newBrowsingHistory);
        }
    }
}